package org.jaaksi.customviewdemo.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.toColorInt
import extension.dp


class BMIView(context: Context?, attrs: AttributeSet?) :
    View(context, attrs) {

    val paint = Paint()
    val rectF = RectF()

    //    val strokeWith = 50 * 2f
    val colors = arrayListOf(
        "#436DFF".toColorInt(),
        "#2294EA".toColorInt(),
        "#53AEF5".toColorInt(),
        "#A8C526".toColorInt(),
        "#FECD2E".toColorInt(),
        "#FD9845".toColorInt(),
        "#F67D3C".toColorInt(),
    )

    var angle: Float = 180.0f
    var center = 0f

    // 圆弧宽度
    var roundWidth = 60f.dp

    // 内圆半径
    var insideRadius = 70f.dp
    var pointerOffset = 15f.dp

    // RectF
    var rectFRadius = 0f
    var sweepAngle = 180f / colors.size
    var textRectF: Rect = Rect()

    val path = Path()

    init {
        paint.apply {
            style = Paint.Style.STROKE
            isAntiAlias = true
//            strokeWidth = roundWidth
            textSize = 30f.dp.toFloat()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        paint.getTextBounds("1234567890", 0, 10, textRectF)
        setMeasuredDimension(
            (roundWidth + insideRadius + textRectF.height()).toInt() * 2, //向上去整
            (roundWidth + insideRadius + pointerOffset + textRectF.height()).toInt()
        )
    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        center = w / 2f
        rectFRadius = center - roundWidth / 2 - textRectF.height()
        rectF.set(
            center - rectFRadius,
            center - rectFRadius,
            center + rectFRadius,
            center + rectFRadius,
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // resume的时候会重绘，这里要重置数据
        angle = 180f
        paint.strokeWidth = roundWidth
        colors.forEachIndexed { index, color ->
            paint.color = color
            // rectF是圆弧的边界点。由于画笔有宽度，所以实际对应的是圆弧厚度的中心点.如果圆弧厚度为1，就是边界点
            // userCenter控制是否绘制弧形起止位置与中心点的连线，角度坐标系x轴右边是0,顺时针
            canvas.drawArc(
                rectF,
                angle,
                sweepAngle,
                false,
                paint
            )
//            canvas.drawTextOnPath("$angle",)
            angle += sweepAngle
        }
        paint.color = Color.RED
        paint.strokeWidth = 1f
        canvas.drawRect(rectF, paint)
    }

}